<template>
    <div class="crm-expense-container">
        <el-card shadow="hover" class="mb10" v-auth="'crm:expense:list'">
            <el-form :inline="true" :model="search">
                <el-form-item>
                    <el-input v-model="search.contractCode" placeholder="请输入合同编号" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.contractName" placeholder="请输入合同名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.expenseName" placeholder="请输入支出主题" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.examineStatus" placeholder="请选择审核状态" multiple clearable class="w100">
                        <el-option label="草稿" value="0"></el-option>
                        <el-option label="审核中" value="1"></el-option>
                        <el-option label="通过" value="2"></el-option>
                        <el-option label="驳回" value="3"></el-option>
                        <el-option label="撤回" value="4"></el-option>
                        <el-option label="作废" value="5"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.timefield" placeholder="请选择时间" class="w100">
                        <el-option label="创建时间" value="createTime"></el-option>
                        <el-option label="申请日期" value="expenseTime"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-date-picker type="daterange" align="right" v-model="dateData.value" :shortcuts="dateData.shortcuts" 
                        unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-search" type="primary" @click="onTableSearch()">查询</el-button>
                    <el-button icon="el-icon-refresh" @click="onResetSearch()">重置</el-button>
                    <el-button v-if="!search.more" @click="onMoreSearch(true)" type="primary" link>更多</el-button>
                    <el-button v-if="search.more" @click="onMoreSearch(false)" type="info" link>收起</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card shadow="hover">
            <el-button v-auth="'crm:expense:add'" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAddCrmExpense()">新增</el-button>
            <!-- <el-button v-auth="'crm:expense:edit'" type="primary" class="ml10" icon="el-icon-edit" @click="onOpenEditCrmExpense()" :disabled="tableData.selections.length != 1">修改</el-button> -->
            <!-- <el-button v-auth="'crm:expense:remove'" type="primary" class="ml10" icon="el-icon-delete" @click="onTabelRowsDel()" :disabled="tableData.selections.length <= 0">删除</el-button> -->
            <el-table ref="tableCrmExpenseRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id">
                <el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="index" align="center" width="50" show-overflow-tooltip>
                    <template #header>
                        <!-- 使用 el-popover 包裹 el-checkbox-group -->
                        <el-popover placement="bottom-start" :width="100" trigger="click">
                            <template #reference>
                                <!-- 点击触发器：这里放置图标 -->
                                <svg-icon name="el-icon-setting" style="cursor: pointer;"></svg-icon>
                            </template>
                            <!-- el-checkbox-group 放置在此处 -->
                            <el-checkbox-group v-model="tableData.header.selections">
                                <el-checkbox v-for="item in tableData.header.data" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
                            </el-checkbox-group>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column label="合同编号" prop="contractCode" v-if="tableData.header.selections.includes('contractCode')" show-overflow-tooltip></el-table-column>
                <el-table-column label="合同名称" prop="contractName" v-if="tableData.header.selections.includes('contractName')" show-overflow-tooltip></el-table-column>
                <el-table-column label="支出主题" prop="expenseName" v-if="tableData.header.selections.includes('expenseName')" show-overflow-tooltip></el-table-column>
                <el-table-column label="申请人" prop="ownerName" v-if="tableData.header.selections.includes('ownerName')" show-overflow-tooltip></el-table-column>
                <el-table-column label="支出金额" prop="expenseAmount" v-if="tableData.header.selections.includes('expenseAmount')" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{scope.row.expenseAmount}} 元</span>
                    </template>
                </el-table-column>
                <el-table-column label="申请日期" prop="expenseTime" v-if="tableData.header.selections.includes('expenseTime')" show-overflow-tooltip></el-table-column>
                <el-table-column label="是否开票" prop="hasInvoice" v-if="tableData.header.selections.includes('hasInvoice')" show-overflow-tooltip>
                    <template #default="scope">
                        <span class="color-primary" v-if="scope.row.hasInvoice">是</span>
                        <span class="color-info" v-else>否</span>
                    </template>
                </el-table-column>
                <el-table-column label="审核状态" prop="examineStatus" v-if="tableData.header.selections.includes('examineStatus')" width="80" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.examineStatus == '0'" class="color-primary">草稿</span>
                        <span v-else-if="scope.row.examineStatus == '1'" class="color-warning">审核中</span>
                        <span v-else-if="scope.row.examineStatus == '2'" class="color-success">通过</span>
                        <span v-else-if="scope.row.examineStatus == '3'" class="color-danger">驳回</span>
                        <span v-else-if="scope.row.examineStatus == '4'" class="color-primary">撤回</span>
                        <span v-else-if="scope.row.examineStatus == '5'" class="color-info">作废</span>
                    </template>
                </el-table-column>
                <el-table-column label="所属用户" prop="userName" v-if="tableData.header.selections.includes('userName')" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="所属部门" prop="deptName" v-if="tableData.header.selections.includes('deptName')" width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" prop="createTime" v-if="tableData.header.selections.includes('createTime')" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" fixed="right" show-overflow-tooltip width="130" v-auths="['crm:expense:info', 'crm:expense:edit', 'crm:expense:remove', 'crm:expense:commited', 'crm:expense:approved', 'crm:expense:rejected', 'crm:expense:canceled', 'crm:expense:discard', 'crm:expense:change']">
                    <template #default="scope">
                        <el-button v-auth="'crm:expense:info'" type="primary" link @click="onOpenInfoCrmExpense(scope.row)">详情</el-button>
                        <el-dropdown class="ml10" style="vertical-align:unset" v-auths="['crm:expense:edit', 'crm:expense:remove', 'crm:expense:commited', 'crm:expense:approved', 'crm:expense:rejected', 'crm:expense:canceled', 'crm:expense:discard', 'crm:expense:change']">
                            <span class="el-dropdown-link">
                                <el-button type="primary" link>更多 <i class="fa fa-angle-down"></i></el-button>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <div v-auth="'crm:expense:edit'" v-show="['0','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenEditCrmExpense(scope.row)">修改</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:expense:remove'" v-show="['0','3','4','5'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onTabelRowDel(scope.row)">删除</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:expense:commited'" v-show="['0','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '1')">提交</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:expense:approved'" v-show="['1'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '2')">通过</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:expense:rejected'" v-show="['1','2'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '3')">驳回</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:expense:canceled'" v-show="['1'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '4')">撤回</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:expense:discard'" v-show="['0','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '5')">作废</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:expense:change'">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenChangeCrmExpense(scope.row)">变更</el-button>
                                        </el-dropdown-item>
                                    </div>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onPageSizeChange"
                @current-change="onPageCurrentChange"
                class="mt15"
                :pager-count="5"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                v-model:current-page="search.pageNum"
                v-model:page-size="search.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.total"
            >
            </el-pagination>
        </el-card>
        <AddCrmExpense ref="addCrmExpenseRef" @submit="onTableSearch"/>
        <EditCrmExpense ref="editCrmExpenseRef" @submit="onTableSearch"/>
        <ChangeCrmExpense ref="changeCrmExpenseRef" @submit="onTableSearch"/>
        <ApproveCrmExpense ref="approveCrmExpenseRef" @submit="onTableSearch"/>
        <InfoCrmExpense ref="infoCrmExpenseRef"></InfoCrmExpense>
    </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, watch, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Local } from '/@/utils/storage';
import AddCrmExpense from '/@/views/crm/expense/addCrmExpense.vue';
import EditCrmExpense from '/@/views/crm/expense/editCrmExpense.vue';
import ChangeCrmExpense from '/@/views/crm/expense/changeCrmExpense.vue';
import ApproveCrmExpense from '/@/views/crm/expense/approveCrmExpense.vue';
import InfoCrmExpense from '/@/views/crm/expense/infoCrmExpense.vue';
import { getCrmExpenseList, delCrmExpense, examineCrmExpense } from '/@/api/crm/expense/index';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
export default {
    name: 'crm/expense',
    components: { AddCrmExpense, EditCrmExpense, ChangeCrmExpense, ApproveCrmExpense, InfoCrmExpense },
    setup() {
        const tableCrmExpenseRef = ref();
        const addCrmExpenseRef = ref();
        const editCrmExpenseRef = ref();
        const changeCrmExpenseRef = ref();
        const approveCrmExpenseRef = ref();
        const infoCrmExpenseRef = ref();
        const state = reactive({
            search:{
                contractCode: undefined,
                contractName: undefined,
                expenseName: undefined,
                examineStatus: [],
                timefield: 'createTime',
                startTime: '',
                endTime: '',
                orderBy: 'createTime',
				isAsc: 'desc',
                pageNum: 1,
                pageSize: 10,
                more: false,
            },
            dateData: {
                value: [],
                shortcuts: getDateRangeShortcuts()
            },
            tableData: {
                selections: [],//选中的行数据
                data: [],
                total: 0,
                loading: false,
                header: {
                    selections: ['contractCode', 'contractName', 'expenseName', 'ownerName', 'expenseAmount', 'expenseTime', 'hasInvoice', 'examineStatus', 'userName', 'deptName', 'createTime'],
                    data: [
                        { label: '合同编号', value: 'contractCode' },
                        { label: '合同名称', value: 'contractName' },
                        { label: '支出主题', value: 'expenseName' },
                        { label: '申请人', value: 'ownerName' },
                        { label: '支出金额', value: 'expenseAmount' },
                        { label: '申请日期', value: 'expenseTime' },
                        { label: '是否开票', value: 'hasInvoice' },
                        { label: '审核状态', value: 'examineStatus' },
                        { label: '所属用户', value: 'userName' },
                        { label: '所属部门', value: 'deptName' },
                        { label: '创建时间', value: 'createTime' },
                    ],
                }
            }
        });

        const loadTableData = (params) => {
            const search = { ...state.search, ...params };
            const examineStatusStr = search.examineStatus.join(',');
            getCrmExpenseList({
                ...search,
                examineStatus: examineStatusStr,
            }).then((res) => {
                if(res.code == 0){
                    state.tableData.data = res.data;
                    state.tableData.total = res.total;
                    tableCrmExpenseRef.value.clearSelection();
                }
            });
        }

        //查询
        const onTableSearch = () => {
            if(state.dateData.value.length == 2){
                state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
                state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
            }
            loadTableData(state.search);
        }
        //重置
        const onResetSearch = () => {
            state.dateData.value = [];
            state.search.contractCode = undefined;
            state.search.contractName = undefined;
            state.search.expenseName = undefined;
            state.search.examineStatus = [];
            state.search.startTime = undefined;
            state.search.endTime = undefined;
            state.search.pageNum = 1;
            state.search.pageSize = 10;
            loadTableData(state.search);
        }
        const onMoreSearch = (more: boolean) => {
            state.search.more = more;
        };
        // 监听表格选中行
        const onTableSelectionChange = (selections) =>{
            state.tableData.selections = selections;
        };
        // 每页显示数据大小改变
        const onPageSizeChange = (val: number) => {
            state.search.pageSize = val;
            loadTableData(state.search);
        };
        // 页码改变
        const onPageCurrentChange = (val: number) => {
            state.search.pageNum = val;
            loadTableData(state.search);
        };
        // 打开新增弹窗
        const onOpenAddCrmExpense = (row: object) => {
            addCrmExpenseRef.value.openDialog(row);
        };
        // 打开编辑弹窗
        const onOpenEditCrmExpense = (row: object) => {
            row = row || state.tableData.selections[0];
            editCrmExpenseRef.value.openDialog(row);
        };
        // 打开变更弹窗
        const onOpenChangeCrmExpense = (row: object) => {
            row = row || state.tableData.selections[0];
            changeCrmExpenseRef.value.openDialog(row);
        };
        // 删除选中行
        const onTabelRowsDel = () => {
            const ids = state.tableData.selections.map(item => item.id);
            if(ids && ids.length > 0){
                ElMessageBox.confirm('确定删除选中的支出信息吗？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    delCrmExpense(ids).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('删除成功');
                            loadTableData();
                        }
                    });
                }).catch(() => {});
            }
        };
        // 删除当前行
        const onTabelRowDel = (row: object) => {
            ElMessageBox.confirm('确定删除该条支出信息吗？', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                delCrmExpense([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('删除成功');
                        loadTableData();
                    }
                });
            }).catch(() => {});
        };

        const examineStatusText = (status: String) => {
            const statusMap = {
                '0': '草稿',
                '1': '提交',
                '2': '通过',
                '3': '驳回',
                '4': '撤回',
                '5': '作废'
            };
            return statusMap[status] || '未知';
        };

        const onOpenExamineRecordStatus = (row: object, status: String) => {
            if(['1', '4', '5'].includes(status)){
                ElMessageBox.confirm(`确认【${ examineStatusText(status) }】操作吗？`, '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    examineCrmExpense({ examineTargetId: row.id, status: status }).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('操作成功');
                            loadTableData({});
                        }
                    });
                }).catch(() => {});
            }else if('3' === status){
                ElMessageBox.prompt('请输入驳回原因：', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then((message) => {
                    if (!message.value || message.value.trim() === '') {
                        ElMessage.error('驳回原因不能为空，请重新输入！');
                    } else {
                        examineCrmExpense({ examineTargetId: row.id, status: status, examineReason: message.value }).then((res) => {
                            if(res.code === 0){
                                ElMessage.success('操作成功');
                                loadTableData({});
                            }
                        });
                    }
                }).catch(() => {});
            }else if('2' === status){
                approveCrmExpenseRef.value.openDialog(row);
            }
        };
        
        const onOpenInfoCrmExpense = (row: object) => {
            row = row || state.tableData.selections[0];
            infoCrmExpenseRef.value.openDialog(row);
        };

        // 页面加载时
        onMounted(() => {
            const selections = Local.get('crm_expense_header_selections');
            if(selections){
                state.tableData.selections = selections;
            }
            loadTableData({});
        });

        watch(() => state.tableData.header.selections, (selections) => {
            nextTick(() => {
                Local.set('crm_expense_header_selections', selections)
                tableCrmExpenseRef.value.doLayout();
            });
        }, { deep: true });

        return {
            tableCrmExpenseRef,
            addCrmExpenseRef,
            editCrmExpenseRef,
            changeCrmExpenseRef,
            approveCrmExpenseRef,
            infoCrmExpenseRef,
            onTableSearch,
            onResetSearch,
            onMoreSearch,
            onTableSelectionChange,
            onPageSizeChange,
            onPageCurrentChange,
            onOpenAddCrmExpense,
            onOpenEditCrmExpense,
            onTabelRowsDel,
            onTabelRowDel,
            onOpenInfoCrmExpense,
            onOpenExamineRecordStatus,
            onOpenChangeCrmExpense,
            ...toRefs(state),
        };
    },
};
</script>